package date0704pm;

import cn.edu.ecut.util.DatabaseType;
import cn.edu.ecut.util.JdbcHelper;
import cn.edu.ecut.util.Runner;


public class JdbcTest23 {

	public static void main(String[] args) {
		
		JdbcHelper h = JdbcHelper.getInstance( DatabaseType.MYSQL ) ;
		
		/*
		{ // 事务开始
			String reduce = "UPDATE t_accounts SET balance = balance - 500 WHERE account = '400200300100' " ;
			h.update( reduce );
			String grow = "UPDATE t_accounts SET balance = balance + 500 WHERE account = '100200300400' " ;
			h.update( grow );
		} // 事务终结 ( 提交事务 或 回滚事务 )
		*/
		
		// 通过匿名内部类实现 Runner接口的doInTransaction方法来执行多个DML操作
		Runner r = new Runner(){
			public void doInTransaction() throws Exception {
				String reduce = "UPDATE t_accounts SET balance = balance - 500 WHERE account = ? " ;
				h.update( reduce , "400200300100" );
				
				Thread.sleep( 10000 );
				
				System.out.println( 5 / 0 );
				
				String grow = "UPDATE t_accounts SET balance = balance + 500 WHERE account = ? " ;
				h.update( grow , "100200300400" );
			}
		};
		
		// 通过 execute 提供的支持，保证多个DML操作在同一个事务中执行
		h.execute( r ); // execute 方法内部提供了事务支持: 禁用自动提交、开启新事务、提交或回滚事务、启用自动提交
		
		h.release();

	}

}
